package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.exception.CustomException;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/sendMsg")
    public R sendMsg(HttpSession session, @RequestBody Map<String, String> map) {
        //1. 获取手机号
        String phone = map.get("phone");
        //1.1 尝试从缓存中读取对应的验证码
        Object codeInRedis = redisTemplate.opsForValue().get(phone);

        if (codeInRedis != null ) {
            Long time = redisTemplate.getExpire(phone);
//            return R.error("操作过于频繁,请" + time + "后重试");
//            return R.success("操作过于频繁,请" + time + "后重试");
           throw new CustomException("异常:操作过于频繁,请" + time + "后重试");
        }
        //2. 随机生成验证码
//        ValidateCodeUtils.generateValidateCode4String(4);
        String code = "1234";
        //3. 调用工具类发送短信验证码
        //SMSUtils.sendMessage("czz的博客", "SMS_277875043", phone, code);
        //4. 把验证码存入session key:phone  value:验证码
        // session.setAttribute(phone, code);
        // 修改,验证码不需要存到session里,存到缓存里就可以了
        redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);

        return R.success("发送短信验证码成功");
    }

    @PostMapping("/login")
    public R login(HttpSession session, @RequestBody Map<String, String> map) {
        //1. 获取用户输入手机号，验证码
        String phone = map.get("phone");
        String code = map.get("code");
        //2. 获取session中的验证码 --> 获取缓存中的验证码
//        Object sessionCode = session.getAttribute(phone);
        Object redisCode = redisTemplate.opsForValue().get(phone);
        if (redisCode == null) {
            throw new CustomException("验证码错误");
        }
        //3. 比对用户输入的验证码和session中的验证码  -->> 和缓存中的验证码做对比
        if (!redisCode.equals(code)) {
            //3.1 如果不一致，抛出业务异常
            throw new CustomException("验证码错误");
        }

        //4. 根据手机号判断用户是否存在
        LambdaQueryWrapper<User> ulqw = new LambdaQueryWrapper<>();
        ulqw.eq(User::getPhone, phone);
        User user = userService.getOne(ulqw);
        if (user == null) {
            //4.1 如果不存在？注册（添加到数据库）
            // 不用新建一个user,直接把新user赋值给被判断的user
            user = new User();
            user.setPhone(phone);
            // 设置用户的状态为1
            user.setStatus(1);
            userService.save(user);
        }

        //5. 判断用户状态
        if (user.getStatus() == 0) {
            //5.1 如果已禁用，不允许，抛出业务异常
            throw new CustomException("该用户已被封号");
        }

        //6. 用户登陆成功，把id存入session
        session.setAttribute("userId", user.getId());
        //7. 移除session中的验证码 -->> 移除缓存中的验证码信息
//        session.removeAttribute("phone");
        redisTemplate.delete(phone);
        return R.success("登陆成功");
    }


    @PostMapping("loginout")
    public R logout(HttpSession session) {
        log.info("退出登录");
        session.removeAttribute("userId");
        return R.success("拜拜");
    }

}